﻿using Common.Exceptions;
using Common.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Wallpaper.Data.Dal;
using Wallpaper.Data.IDal;
using Wallpaper.Models.DTOs.Base;
using Wallpaper.Models.DTOs.Requests.Category;
using Wallpaper.Models.DTOs.Responses.Carousel;
using Wallpaper.Models.DTOs.Responses.Category;
using Wallpaper.Models.Entities;
using Wallpaper.Models.Options;
using Wallpaper.Services.IService;

namespace Wallpaper.Services.Service
{
    public class CategoryService : ICategoryService
    {
        readonly ICategoryDal _categoryDal;

        public CategoryService(ICategoryDal categoryDal)
        {
            _categoryDal = categoryDal;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="BusinessException"></exception>
        public async Task<bool> CreateAsync(CategoryRequest request)
        {
            bool exists = await _categoryDal.ExistsByNameAsync(request.Name);
            if (exists)
            {
                throw new BusinessException($"分类名称 '{request.Name}' 已存在", 400);
            }
            Category category = new Category
            {
                Id = Guid.NewGuid().ToString(),
                Name = request.Name,
                Sort = request.Sort,
                CategorylUrl=request.CategorylUrl,
                IsEnabled=request.IsEnabled
            };

            return await _categoryDal.CreateEntityAsync(category);
        }

        /// <summary>
        /// 根据id删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> DeleteById(string id)
        {
            return await _categoryDal.DeleteByIdAsync(id);
        }


        /// <summary>
        /// 获取分类封面
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<List<CoverResponse>> getCoverAsync()
        {
            var query = _categoryDal.GetQueryable().Where(c => c.IsEnabled && !c.IsDeleted);
            var response = await query.Select(b => new CoverResponse
            {
                Id = b.Id,
                CategoryUrl = b.CategorylUrl,
                Title = b.Name
            }).ToListAsync();
            return response;
        }

        /// <summary>
        /// 获取下列
        /// </summary>
        /// <returns></returns>
        public async Task<List<OptionsResponse>> OptionsAsync()
        {
            var categories = _categoryDal.GetQueryable();

            return await categories
                .Where(c => c.IsEnabled && !c.IsDeleted) 
                .OrderBy(c => c.Sort) 
                .Select(c => new OptionsResponse
                {
                    Value = c.Id,      
                    Label = c.Name     
                })
                .ToListAsync();
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<PagedResult<CategoryResponse>> PageAsync(QueryRequest request)
        {
            var query = _categoryDal.GetQueryable();
            // 关键词搜索
            if (!string.IsNullOrWhiteSpace(request.Keyword))
            {
                query = query.Where(c => c.Name.Contains(request.Keyword));
            }
            // 启用状态筛选
            if (request.IsEnabled.HasValue)
            {
                query = query.Where(r => r.IsEnabled == request.IsEnabled.Value);
            }
            // 获取总数
            var totalCount = await query.CountAsync();

            // 分页
            var items = await query
            .Skip((request.Page - 1) * request.PageSize)
            .Take(request.PageSize)
            .OrderBy(r=>r.Sort)
       .Select(c => new CategoryResponse  // 映射到 DTO
       {
           Id = c.Id,
           Name = c.Name,
           Sort=c.Sort,
           CategorylUrl=c.CategorylUrl,
           IsEnabled=c.IsEnabled,
           CreatedTime=c.CreatedAt,
           UpdatedTime=c.UpdatedAt
          
       })
       .ToListAsync();

            return new PagedResult<CategoryResponse>
            {
                Page = request.Page,
                PageSize = request.PageSize,
                TotalCount = totalCount,
                Items = items
            };
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="category"></param>
        /// <returns></returns>
        /// <exception cref="BusinessException"></exception>
        public async Task<bool> UpdateAsync(string id, CategoryRequest request)
        {
            // 1. 获取分类
            var category = await _categoryDal.GetByIdAsync(id);
            if (category == null)
            {
                throw new BusinessException("该分类不存在", 404);
            }

            // 2. 检查名称冲突
            if (category.Name != request.Name &&
                await _categoryDal.ExistsByNameAsync(request.Name, id))
            {
                throw new BusinessException($"分类名称 '{request.Name}' 已存在", 400);
            }

            // 3. 更新并保存
            category.Name = request.Name;
            category.Sort = request.Sort;
            category.CategorylUrl = request.CategorylUrl;
            category.IsEnabled = request.IsEnabled;

            return await _categoryDal.UpdateEntityAsync(category);
        }
    }
}
